<?php

namespace App\Service\Auth;

use App\Service\BaseService;
use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\Helper;
use App\Model\ProfileVerifyLog;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;

/**
 * 阿里云-实名认证获取token
 */
class AliVerfyTokenService extends BaseService
{
    protected function RoVerifyList()
    {
        return [
            'real_name' => '|string',
            'id_card' => '|string',
            'vrfy_type' => '|string'
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $vrfyType = $this->request->input('vrfy_type', 1);
        switch ($vrfyType) {
                //实名认证
            case 1:
                $realName = $this->request->input('real_name', '');
                $cardNo = $this->request->input('id_card', '');
                $vrfResult = $this->doRealVrfy($userId, $realName, $cardNo);
                if (isset($vrfResult['ret']) && $vrfResult['ret'] != 0) {
                    return $vrfResult;
                }
                $vrfObject = [
                    "bizType" => config('aliyun.verfScene.real_check'),
                    "bizId" => $bizNo = $this->createBizId($userId),
                    "name" => $realName,
                    'idCardNumber' => $cardNo,
                ];
                break;

                //头像真人认证
            case 2:
                $vrfResult = $this->doAvatarVrfy($userId);
                if (isset($vrfResult['ret']) && $vrfResult['ret'] != 0) {
                    return $vrfResult;
                }
                $vrfObject = [
                    "bizType" => config('aliyun.verfScene.avatar_check'),
                    "bizId" => $bizNo = $this->createBizId($userId),
                    "faceRetainedImageUrl" => $vrfResult['avatar'],
                ];
                break;
        }

        //获取视频验证的token
        $result = AliyunUtil::getVerifyToken($vrfObject);
        if (empty($result->verifyToken)) {
            return $this->setError(ErrorCode::VRF_TOKEN_FAIL, '获取验证token失败,请重新尝试');
        }

        //更新业务ID
        UserProfilePersonal::updateBizNo($userId, $bizNo, $vrfyType);
        log_user_result($userId, "getVerifyToken==Vrftype:{$vrfyType}==VrfObj:" . json_encode($vrfObject) . "==Result:" . json_encode($result));
        return [
            'verfy_token' => $result->verifyToken,
            'biz_no' => $bizNo,
            // 'card_info' => $vrfResult['card_info']
        ];
    }

    /**
     * 照片真人认证
     */
    function doAvatarVrfy($userId)
    {
        $profile = UserProfile::getProfile($userId, false);
        $checkCount = ProfileVerifyLog::checkTodayCount($userId, ProfileVerifyLog::TYPE_REAL_AVATAR);
        $isHost = UserProfile::checkRoleHost($profile->role);
        if (!check_dev_env() && $checkCount >= env('REAL_AVATAR_VRYF_LMT', 3)) {
            return $this->setError(ErrorCode::REAL_AVATAR_LMT, '当日认证已达上限！');
        }

        //认证待审核记录
        ProfileVerifyLog::addRecord(
            $userId,
            ProfileVerifyLog::TYPE_REAL_AVATAR,
            ['avatar' => $profile->avatar],
            ProfileVerifyLog::STATUS_ING
        );

        return [
            'ret' => 0,
            'avatar' => AliyunUtil::IMG_HOST . $profile->avatar,
            'avatar_name' => $profile->avatar
        ];
    }

    /**
     * 实名认证
     */
    function doRealVrfy($userId, $realName, $cardNo)
    {
        if (!$realName || !$cardNo) return $this->setError(ErrorCode::PARAMETER_ERROR, '身份信息相关参数缺失！');

        //身份证是否认证过
        $checkIdCard = UserProfilePersonal::checkIdCard($cardNo);
        if ($checkIdCard) {
            return $this->setError(ErrorCode::ID_CARD_EXITS, '该身份信息已存在！');
        }

        //身份证认证审核
        if (!check_dev_env()) {
            $vrfResult = Helper::verifyIdCard($realName, $cardNo);
            if ($vrfResult['result'] == 0) {
                return $this->setError(ErrorCode::IDCARD_VRF_FAIL, '身份信息验证失败，请重新检查后再输入！');
            }
            if (isset($vrfResult['card_info'])) {
                $grownUp = Helper::verifyIsGrownUp($vrfResult['card_info']['birthday']);
                if (!$grownUp) {
                    return $this->setError(ErrorCode::NOT_GROWN_UP, '你还未满18岁，暂不允许进行认证！');
                }
                $overAge = Helper::verifyIsOverAge($vrfResult['card_info']['birthday']);
                if ($overAge) {
                    return $this->setError(ErrorCode::NOT_ALLOWED_VRF, '身份信息暂未达到实名认证标准！');
                }
            }
            //男性暂时不允许认证
            $validNames = ['张平安'];
            if (!in_array($realName, $validNames) && isset($vrfResult['card_info']['sex']) && $vrfResult['card_info']['sex'] == '男') {
                return $this->setError(ErrorCode::NOT_ALLOWED_VRF, '暂仅支持女性用户认证！');
            }
        }

        //保存认证的姓名，身份证
        $saveRet = UserProfilePersonal::saveRealnameInfo($userId, $realName, $cardNo);
        return ['ret' => 0];
    }

    /**
     * 创建业务ID
     */
    function createBizId($userId = 0)
    {
        return time() . "_{$userId}";
    }
}
